<template>
  <div class="vr-scene-container">
    <div ref="sceneRef" class="vr-scene"></div>
    <div v-if="loading" class="loading-overlay">
      <div class="loading-text">VR场景加载中...</div>
    </div>
    <div v-if="!isVRSupported && !loading" class="vr-not-supported">
      <div class="error-message">
        <h2>VR不支持</h2>
        <p>您的浏览器不支持WebXR功能，请使用支持WebXR的浏览器，如：</p>
        <ul>
          <li>Chrome 79+ (推荐)</li>
          <li>Edge 79+</li>
          <li>Firefox VR-enabled build</li>
        </ul>
        <p>并确保您已连接VR设备</p>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { initVRScene } from '../../tools/vrSceneUtils';
import { useVRControls } from '../../tools/vrControls';

export default {
  name: 'VRScene',
  setup() {
    const sceneRef = ref(null);
    const loading = ref(true);
    const isVRSupported = ref(false);
    let cleanup = null;

    // 检查WebXR支持
    const checkVRSupport = async () => {
      if ('xr' in navigator) {
        try {
          const isSupported = await navigator.xr.isSessionSupported('immersive-vr');
          isVRSupported.value = isSupported;
          return isSupported;
        } catch (err) {
          console.error('VR支持检查失败:', err);
          return false;
        }
      }
      return false;
    };

    onMounted(async () => {
      const vrSupported = await checkVRSupport();
      
      if (!vrSupported) {
        loading.value = false;
        return;
      }

      if (sceneRef.value) {
        try {
          const { cleanupScene, sceneObjects } = await initVRScene(sceneRef.value);
          
          // 初始化VR控制器
          const controls = useVRControls(sceneObjects);
          sceneObjects.setControls(controls);  // 设置控制器
          
          cleanup = () => {
            cleanupScene();
            controls.dispose();
          };
          
          loading.value = false;
        } catch (error) {
          console.error('VR场景初始化失败:', error);
          loading.value = false;
        }
      }
    });

    onBeforeUnmount(() => {
      if (cleanup) {
        cleanup();
      }
    });

    return {
      sceneRef,
      loading,
      isVRSupported
    };
  }
};
</script>

<style lang="less" scoped>
.vr-scene-container {
  width: 100%;
  height: 100%;
  position: relative;
  
  .vr-scene {
    width: 100%;
    height: 100%;
  }

  .loading-overlay,
  .vr-not-supported {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.7);
    display: flex;
    justify-content: center;
    align-items: center;
    color: white;
  }

  .error-message {
    text-align: center;
    padding: 20px;
    
    h2 {
      color: #ff4444;
      margin-bottom: 20px;
    }

    ul {
      list-style: none;
      padding: 0;
      margin: 20px 0;
      
      li {
        margin: 10px 0;
      }
    }
  }
}
</style> 